//
//  CurrentAffairsViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/9/19.
//

import UIKit
import MJRefresh

class CurrentAffairsViewController: BaseViewController {
    var tableView: BaseTableView!
    var suspendBtn: UIButton!
    var buttonStartPosition: CGPoint!
    var emptyView: LYEmptyView!
    var pageNumber = 1
    var dataArray = NSMutableArray()
    var model: CurrentAffairDataModel!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = Theme.F5Color
        self.navBar.title = self.model.name ?? ""
        self.initTableView()
        self.requestConsultationList(isMore: false)
    }
    
    override func viewDidLayoutSubviews() {
          super.viewDidLayoutSubviews()
          if buttonStartPosition == nil {
              buttonStartPosition = suspendBtn.frame.origin
          }
      }
    
    func initTableView(){
        self.tableView = BaseTableView(frame: CGRect(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight - NavBarHight), style: .plain)
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 2
        self.tableView.register(CurrentTableViewCell.self, forCellReuseIdentifier: "CurrentTableViewCell")//汽车时事
        self.view.addSubview(self.tableView)
        
        
        self.suspendBtn = UIButton(frame: CGRect(x: 14, y: kScreenHeight - 145, width: 34, height: 34))
        self.suspendBtn.setImage(UIImage(named: "icon_suspend"), for: .normal)
        self.suspendBtn.addTarget(self, action: #selector(suspendBtnAntion), for: .touchUpInside)
        self.view.addSubview(self.suspendBtn)
        suspendBtn.isHidden = true
        self.view.bringSubview(toFront: self.suspendBtn)
        
//        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_ :)))
//        suspendBtn.addGestureRecognizer(panGesture)
        
        
      
        self.setUpNoData()
        self.addPullRefreash()
        self.addLoadMoreRefreash()
    }
    
  
    
    ///空视图
    func setUpNoData() {
        self.emptyView = LYEmptyView.emptyActionView(withImageStr: "icon_cassify_empty", titleStr: MMLocalizedString("no_data", comment: "暂无数据"), detailStr: "", btnTitleStr: "") {

        }
        emptyView.titleStr = ""
        emptyView?.subViewMargin = 28
        emptyView?.contentViewOffset = 0
        emptyView.isHidden = true
        self.tableView.ly_emptyView = self.emptyView
    }

    ///空视图
    func willShowEmptyView() {
        if self.dataArray.count == 0 {
            self.tableView.mj_footer?.isHidden = true
            self.emptyView.isHidden = false
            self.emptyView?.titleStr = MMLocalizedString("no_data", comment: "暂无数据")
        }else{
            self.emptyView.isHidden = true
            self.emptyView?.titleStr = ""
        }
    }
    
    /*
     * 添加头部刷新
     */
    func addPullRefreash()  {
        weak var weakself = self
        self.tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            weakself?.pageNumber = 1
            weakself?.requestConsultationList(isMore: false)
        })
    }
    
    
    //MARK: -  底部刷新
    func addLoadMoreRefreash()  {
        weak var weakself = self
        self.tableView.mj_footer = ExtNoMoreRefreashFooterView.init(refreshingBlock: {
            weakself?.pageNumber = weakself!.pageNumber + 1
            weakself?.requestConsultationList(isMore: true)
        })
    }
        
    
    //MARK: - Request
    //咨询列表
    func requestConsultationList(isMore: Bool){
        self.view.showLoadingHUDText(nil)
        let param = ["articleCategoryId": "\(self.model.id ?? 0)","pageNumber": "\(self.pageNumber)","pageSize": "10"]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.consultationList(param: param),objectType: ArticleModel.self) { data in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            self.view.handleLoading()
            let resultObj = data as! ArticleModel
            if resultObj.code == "1" {
                if isMore == false{
                    self.dataArray.removeAllObjects()
                }
                self.dataArray.addObjects(from: resultObj.data?.content ?? [])
            }
            
            if self.dataArray.count < 10{
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
            }
            
            self.tableView.reloadData()
            self.willShowEmptyView()
        }error: { err in
            self.willShowEmptyView()
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            self.view.handleLoading()
            self.view.makeToast(message: err?.domain ?? MMLocalizedString("request_failed", comment: "请求失败，请稍候再试"))
        }
    }
    
    
    //MARK: -Antion
  @objc func suspendBtnAntion(){
        
    }
    
    @objc func handlePan(_ gesture: UIPanGestureRecognizer) {
         let translation = gesture.translation(in: view)
         guard let buttonStartPosition = buttonStartPosition else { return }
         let newPosition = CGPoint(x: buttonStartPosition.x + translation.x, y: buttonStartPosition.y + translation.y)
         suspendBtn.frame.origin = newPosition
     }
    
    
}

extension CurrentAffairsViewController: UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
       
        return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "CurrentTableViewCell", for: indexPath) as! CurrentTableViewCell
        if self.dataArray.count > indexPath.row{
            let model = self.dataArray[indexPath.row] as! ArticleListModel
            cell.setModel(model: model)
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 10))
        headerView.backgroundColor = Theme.F5Color
        return headerView
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 0.01))
        footerView.backgroundColor = .clear
        return footerView
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if self.dataArray.count > indexPath.row{
            let model = self.dataArray[indexPath.row] as! ArticleListModel
            let vc = ArticleDetailsViewController()
            vc.id = "\(model.id ?? 0)"
            vc.titleStr = model.columnName ?? ""
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
}
